const { Controller } = require('egg');
const jwt = require('jsonwebtoken');
class HomeController extends Controller {
    async index() {
        this.ctx.body = 'Hi, Egg ~';
    }

    async login() {
        const { username, password } = this.ctx.request.body;

        let user;
        if (username === 'superadmin' && password === '123456') {
            user = {
                id: 1,
                username: 'superadmin',
                rcode: 'v0',
                rname: '超级管理员',
            };
        } else if (username === 'admin' && password === '123456') {
            user = {
                id: 2,
                username: 'admin',
                rcode: 'v1',
                rname: '管理员',
            };
        } else if (username === 'visitor' && password === '123456') {
            user = {
                id: 3,
                username: 'visitor',
                rcode: 'v2',
                rname: '访客',
            };
        } else {
            this.ctx.body = {
                code: 404,
                message: '用户不存在',
            };
            return;
        }

        // 签名
        const token = jwt.sign(user, '123123123', { expiresIn: '2h' });

        // 返回响应
        this.ctx.body = {
            code: 200,
            data: { token },
            message: '登录成功',
        };
    }

    async register() {
        this.ctx.body = 'register api';
    }
}

module.exports = HomeController;
